package serveur.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import serveur.model.entite.FichierImage;

public class ImageDAO {
	private Connection connexion;

	public ImageDAO(Connection connexion) {
		this.connexion = connexion;
	}
	
	//enregistre une nouvelle image
	public void create(FichierImage image) {
		try {
			PreparedStatement statement = connexion.prepareStatement("INSERT INTO image (reponse) VALUES ('"+image.getReponse()+"')");		
			statement.executeUpdate();
			System.out.println("l'image "+image.getReponse()+" a été enregistrée");
			image.setId(this.getId(image.getReponse()));
		} catch (SQLException e) {
			System.out.println("probleme d'ajout d'image");
			e.printStackTrace();
		}
	}
	
	//recherche une image par sa réponse
	public int getId(String reponse){
		try {
			PreparedStatement statement = connexion.prepareStatement("SELECT * FROM image WHERE reponse='"+reponse+"';");		
			if(statement.execute()){
				ResultSet rs = statement.getResultSet();
				if(rs.next()){
					return rs.getInt("id");
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
	
	//supprime une image
	public void delete(FichierImage image){
		try {
			System.out.println("id image ==> "+image.getId());
			PreparedStatement statement = connexion.prepareStatement("DELETE FROM image WHERE id="+image.getId());		
			statement.execute();
		} catch (SQLException e) {
			System.out.println("probleme de suppression d'image");
			e.printStackTrace();
		}
	}
	
	public String[] findAll(){
		try {
			PreparedStatement stat = connexion.prepareStatement("SELECT count(*) AS nbLignes FROM image ");
			int nb = 0;
			if(stat.execute()){
				ResultSet r = stat.getResultSet();
				if(r.next()){
					nb =r.getInt("nbLignes");
				}
			}
			if(nb > 0){
				PreparedStatement statement = connexion.prepareStatement("SELECT * FROM image;");		
				if(statement.execute()){
					ResultSet rs = statement.getResultSet();
					String[] listeImages = new String[nb];
					int i = 0;
					while(rs.next()){
						listeImages[i] =rs.getInt("id")+"-"+rs.getString("reponse");
						i++;
					}
					return listeImages;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@SuppressWarnings("null")
	public List<FichierImage> findAllImage(){
		try {
			List<FichierImage> list = new ArrayList<FichierImage>();
			PreparedStatement statement = connexion.prepareStatement("SELECT * FROM image");
			ResultSet rs = statement.executeQuery();
			
			while (rs.next()){
				list.add(new FichierImage(rs.getInt("id"), rs.getString("reponse")));
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
